//
//  MYGAcademicDetailHeaderView.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/24.
//

import UIKit
import BetterSegmentedControl
import SDCycleScrollView

class MYGAcademicDetailHeaderView: UIView {
    var cycleScrollView:SDCycleScrollView!
    var detailModel = MYGMeetDetailModel()
    var iconModels = [MYGMYGAcademicIconModel]()
    var dateModels = [MYGMeetDateModel]()
    var getDetailModelCompletion:((MYGMeetDetailDataModel)->Void)?
    var meeting_id = ""
    lazy var itemCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 20
        var leftMargin = 20.0
        layout.itemSize = CGSize(width: 62, height: 62)
        let control = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        control.register(UINib.init(nibName: "MYGAcademicDetailHeaderItemCell", bundle: nil), forCellWithReuseIdentifier: "MYGAcademicDetailHeaderItemCell")
        
        control.showsHorizontalScrollIndicator = false
        control.showsVerticalScrollIndicator = false
        control.backgroundColor = .white
        control.delegate = self
        control.dataSource = self
        control.contentInset = UIEdgeInsets(top: 0, left: leftMargin, bottom: 0, right: leftMargin)
        return control
    }()
    
    lazy var dateCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 11
        var leftMargin = 18.0
        layout.itemSize = CGSize(width: 39, height: 44)
        let control = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        control.register(UINib.init(nibName: "MYGAcademicDetailDateCell", bundle: nil), forCellWithReuseIdentifier: "MYGAcademicDetailDateCell")
        
        control.showsHorizontalScrollIndicator = false
        control.showsVerticalScrollIndicator = false
        control.backgroundColor = .white
        control.delegate = self
        control.dataSource = self
        control.contentInset = UIEdgeInsets(top: 0, left: leftMargin, bottom: 0, right: leftMargin)
        return control
    }()
    
    
    var line: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "eeeeee")
        return control
    }()
    
    var lineBottom: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "eeeeee")
        return control
    }()
    
    lazy var subTileView:MYGAcademicDetailSubtitleView = {
        let control = Bundle.main.loadNibNamed("MYGAcademicDetailSubtitleView", owner: nil)?.first as! MYGAcademicDetailSubtitleView
        control.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 80)
        
        return control
    }()
    
    lazy var segMent:BetterSegmentedControl = {
        let navigationSegmentedControl = BetterSegmentedControl(
            frame: .zero,
            segments: LabelSegment.segments(withTitles: [],
                                            normalTextColor: UIColor.init(hexString: "696969"),
                                            selectedTextColor:.white),
            options:[.backgroundColor(UIColor.init(hexString: "f8f8f8")),
                     .indicatorViewBackgroundColor(UIColor.init(hexString: "ffb701")),
                     .cornerRadius(20),
                     .animationSpringDamping(1.0)])
        
        navigationSegmentedControl.addTarget(self,
                                             action: #selector(navigationSegmentedControlValueChanged(_:)),
                                             for: .valueChanged)
        return navigationSegmentedControl
    }()
    
    private lazy var scrollView: UIScrollView = {
        let sc = UIScrollView()
        sc.bounces = true
        sc.alwaysBounceHorizontal = true
        sc.showsHorizontalScrollIndicator = false
        return sc
    }()
    
    private lazy var contentView: UIView = {
        let contentView = UIView()
        contentView.backgroundColor = .white
        return contentView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        initSubViews()
//        bindData()
    }
    
    func initSubViews() {
        configCycleScrollView()
        addSubview(cycleScrollView)
        cycleScrollView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(150)
        }
        
        addSubview(itemCollectionView)
        itemCollectionView.snp.makeConstraints { make in
            make.top.equalTo(cycleScrollView.snp.bottom).offset(15)
            make.left.right.equalToSuperview()
            make.height.equalTo(62)
        }
        addSubview(line)
        line.snp.makeConstraints { make in
            make.top.equalTo(itemCollectionView.snp.bottom).offset(15)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        addSubview(subTileView)
        subTileView.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(15)
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
        }
        
        addSubview(dateCollectionView)
        dateCollectionView.snp.makeConstraints { make in
            make.top.equalTo(subTileView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        addSubview(lineBottom)
        lineBottom.snp.makeConstraints { make in
            make.top.equalTo(dateCollectionView.snp.bottom).offset(15)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        
        addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(lineBottom.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
        }
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.top.equalTo(lineBottom.snp.bottom).offset(15)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(40)
        }
        contentView.addSubview(segMent)
        segMent.snp.makeConstraints { make in
            make.top.equalTo(lineBottom.snp.bottom).offset(15)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(40)
//            make.verticalEdges.equalToSuperview()
        }
    }
    
    func bindDatwModel(dateModels:[MYGMeetDateModel]) {
        self.dateModels = dateModels
        self.dateCollectionView.reloadData()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.dateCollectionView.delegate?.collectionView?(self.dateCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
        })
    }
    //会议详情
    func getMeetDetail(model:MYGMeetDateModel) {
        self.subTileView.meeting_id = self.meeting_id
        self.subTileView.model = model
        MYGLoading.show()
        MYGNetwork<MYGHomePageAPI, MYGMeetDetailModel>.request(target: .meetingDetail(param: ["meeting_id":meeting_id,"date":model.date])) {[weak self] result in
            MYGLoading.hide()
            guard let `self` = self else {return}
            self.detailModel = result
            self.subTileView.reserveBtn.isHidden = result.is_sign == 1

            self.bindData()

        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    func bindData() {
        iconModels.removeAll()
        
//        var model = MYGMYGAcademicIconModel()
//        model.imageName = "academic_about"
//        model.title = "关于会议"
//        iconModels.append(model)
        
        var model1 = MYGMYGAcademicIconModel()
        model1.imageName = "academic_date"
        model1.title = "日程一览"
        iconModels.append(model1)
        
        var model2 = MYGMYGAcademicIconModel()
        model2.imageName = "academic_search"
        model2.title = "讲者检索"
        iconModels.append(model2)
        
        var model3 = MYGMYGAcademicIconModel()
        model3.imageName = "academic_live"
        model3.title = "会议直播"
        iconModels.append(model3)
        
//        var model4 = MYGMYGAcademicIconModel()
//        model4.imageName = "academic_photo"
//        model4.title = "照片直播"
//        iconModels.append(model4)
        
        itemCollectionView.reloadData()
        
        var titles = [String]()
        for(_,obj) in self.detailModel.data.enumerated() {
            titles.append(obj.roomCn)
        }
        segMent.segments = LabelSegment.segments(withTitles: titles,
                                    normalTextColor: UIColor.init(hexString: "696969"),
                                    selectedTextColor:.white)
        
        let imagesURLStrings = [self.detailModel.image]
        cycleScrollView.imageURLStringsGroup = imagesURLStrings
        
        if let c = getDetailModelCompletion {
            c(self.detailModel.data.first!)
        }
    }
    
    func configCycleScrollView() {
        cycleScrollView = SDCycleScrollView.init(frame: CGRect.init(x: 15, y: 0, width: screenWidth - 30, height: 150), delegate: self, placeholderImage: UIImage(named: ""))
        cycleScrollView?.currentPageDotColor = .white
        cycleScrollView?.pageDotColor = .gray
        cycleScrollView?.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated
        cycleScrollView.layer.cornerRadius = 5
        cycleScrollView.layer.masksToBounds = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func navigationSegmentedControlValueChanged(_ sender: BetterSegmentedControl) {
        //回调出去 MYGMeetDetailDataModel 
        let model = self.detailModel.data[sender.index]
        self.getDetailModelCompletion?(model)
    }
}

extension MYGAcademicDetailHeaderView:SDCycleScrollViewDelegate {
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        
    }
}


extension MYGAcademicDetailHeaderView:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == self.itemCollectionView {
            let model = iconModels[indexPath.row]
            if model.title == "讲者检索" {
                let vc = MYGSpeakerSearchVC()
                vc.meeting_id = meeting_id
                self.rootResponsder().navigationController?.pushViewController(vc, animated: true)
            }
            if model.title == "日程一览" {
                let vc = MYGMeetScheduleViewController()
                vc.meeting_id = meeting_id
                self.rootResponsder().navigationController?.pushViewController(vc, animated: true)
            }
            if model.title == "会议直播" {
                let vc = MYGAcademicConferenceLiverRootVC()//直播
//                let vc = MYGAcademicConferenceReserveVC() //倒计时
                vc.meeting_id = meeting_id
                vc.topImageUrl = self.detailModel.image
                vc.isHiddenBtn = self.detailModel.is_sign == 1
                vc.sing_count = self.detailModel.sign_count
                self.rootResponsder().navigationController?.pushViewController(vc, animated: true)
            }
            
            
        }else {
            let model = self.dateModels[indexPath.row]
            self.dateModels = self.dateModels.map({ obj in
                var result = obj
                result.isSelected = false
                if model.date == obj.date {
                    result.isSelected = true
                }
                return result
            })
            self.dateCollectionView.reloadData()
            getMeetDetail(model: model)
        }
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == self.itemCollectionView {
            return iconModels.count
        }else {
            return dateModels.count
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionView == self.itemCollectionView {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGAcademicDetailHeaderItemCell", for: indexPath) as! MYGAcademicDetailHeaderItemCell
            let model = iconModels[indexPath.row]
            cell.model = model
            return cell
        }else {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGAcademicDetailDateCell", for: indexPath) as! MYGAcademicDetailDateCell
            let model = dateModels[indexPath.row]
            cell.model = model
            return cell
        }
    }  

}
